<?php

namespace backend\controllers;

use app\models\AsrCustomer;
use backend\controllers\CommonController;
use common\helps\UploadFiles;
use moonland\phpexcel\Excel;
use Yii;
use app\models\AsrMobile;
use app\models\search\AsrMobileSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;

/**
 * AsrMobileController implements the CRUD actions for AsrMobile model.
 */
class AsrMobileController extends CommonController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all AsrMobile models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new AsrMobileSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $this->pagesDo($dataProvider);
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single AsrMobile model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new AsrMobile model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new AsrMobile();

        if ($model->load(Yii::$app->request->post()) ) {
            $model->file = UploadedFile::getInstances($model, 'file');
            if(!empty($model->file)){
                //开启事务
                $connection = yii::$app->getDb();
                $transaction = $connection->beginTransaction();
                //先保存asr_mobile表；
                $model->mobile_num = 0;
                $model->belong = 1;
                $getExel = Excel::import([
                    'file1'=>$model->file[0]->tempName,
                ]);
                $model->file = $model->file[0]->name;
                $model->save();
                $array_key = [
                    '公司名称' => "company_name",
                    '联系人' => "username",
                    '联系电话' => "phone_num",
                    '地址' => "address",
                    '职位' => "job",
                    '性别' => "sex",
                    '备注' => "remark",
                ];
                $model = $model->find()->where('1=1')->orderBy('mobile_id desc')->one();
                $mobile_id = $model->mobile_id;
                foreach($getExel['file1'] as $attributes)
                {
                    foreach($attributes as $k=>$v)
                    {
                        $attributes_new[$array_key[$k]] = "".$v;
                    }
                    $asrCustomer = new AsrCustomer();
                    $asrCustomer->mobile_id = $mobile_id;
                    if($attributes_new['sex']=='男' ){//1男2女
                        $attributes_new['sex'] = 1;
                    }else{
                        $attributes_new['sex'] = 2;
                    }
                    $attributes_new['phone_num'] = (int)$attributes_new['phone_num'];
                    $asrCustomer->setAttributes($attributes_new);
                    $asrCustomer->save();
                }
                $model->updateAttributes(['mobile_num'=>count($getExel['file1'])]);
                $transaction->commit();
                //事务完成，一次性提交
            }
            echo Yii::$app->session->setFlash('success','导入电话本成功！');
            return $this->redirect(['index', 'id' => $model->mobile_id]);
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

    /**
     *
     * 将数据导出到本地，格式为exel/csv
     * @param unknown $id
     */
    public function actionDownload()
    {
        $model = new AsrMobile();
        Excel::export([
            'models'=>$model,
            'fileName'=>'template',
            'columns'=>[
                'company_name',
                'username',
                'phone_num',
                'address',
                'job',
                'sex',
                'remark',
            ],
            'headers'=>[
                'company_name'=>'公司名称',
                'username'=>'联系人',
                'phone_num'=>'联系电话',
                'address'=>'地址',
                'job'=>'职位',
                'sex'=>'性别',
                'remark'=>'备注',
            ]
        ]);
    }

    /**
     * Updates an existing AsrMobile model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            echo Yii::$app->session->setFlash('success','修改成功！');
            return $this->redirect(['index', 'id' => $model->mobile_id]);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing AsrMobile model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the AsrMobile model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return AsrMobile the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = AsrMobile::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
